﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace YuFeng.Web.Filters
{
    public class UserLoginFilter : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(LoginUser), inherit: true)
                                        || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(LoginUser), inherit: true);

            if (!skipAuthorization)
            {
                var userService = DependencyResolver.Current.GetService<YuFeng.Services.User.IUserService>();
                var currentUser = SessionContext.CurrentUser;
                if (currentUser == null)
                {
                    var url = new UrlHelper(filterContext.RequestContext);
                    filterContext.Result = new RedirectResult(url.Action("Logon", "Auth", new
                    {
                        area = "Admin",
                        returnUrl = url.Action("Home", "Index")
                    }));
                }
                else
                {
                    var user = userService.GetUserByName(currentUser.Name);
                    if (user == null)
                    {
                        var url = new UrlHelper(filterContext.RequestContext);
                        filterContext.Result = new RedirectResult(url.Action("Logon", "Auth", new
                        {
                            area = "Admin",
                            returnUrl = url.Action("Home", "Index")
                        }));
                    }
                }

            }
        }
    }
    public class LoginUser : Attribute { }
}